# -*- coding: utf-8 -*-
"""
PyQt6主窗口实现
实现现代化深色主题的B站视频下载器界面
"""

import os
import sys
from typing import Optional

from PyQt6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
    QLabel, QLineEdit, QPushButton, QComboBox, QTextEdit,
    QGroupBox, QFrame, QProgressBar, QFileDialog, QMessageBox,
    QSizePolicy, QSpacerItem
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QTimer, QSize
from PyQt6.QtGui import QFont, QPixmap, QIcon, QPalette, QColor

# 导入样式
from .styles.theme import COLORS, get_color

class MainWindowQt(QMainWindow):
    """
    主窗口类 - 实现现代化深色主题UI
    """
    
    def __init__(self):
        super().__init__()
        self.download_path = os.path.expanduser("~/Downloads")  # 默认下载路径
        self.video_info = None  # 视频信息
        self.is_downloading = False  # 下载状态
        
        self.init_ui()
        self.setup_connections()
        
    def init_ui(self):
        """
        初始化用户界面
        """
        # 设置窗口属性
        self.setWindowTitle("Bilibili 视频下载器")
        self.setMinimumSize(900, 700)
        self.resize(1000, 750)
        
        # 设置窗口图标（如果有的话）
        # self.setWindowIcon(QIcon("icon.png"))
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setSpacing(20)
        main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 创建各个区域
        self.create_url_input_section(main_layout)
        self.create_video_info_section(main_layout)
        self.create_download_settings_section(main_layout)
        self.create_control_buttons_section(main_layout)
        self.create_download_log_section(main_layout)
        
        # 设置状态栏
        self.statusBar().showMessage("就绪")
        
    def create_url_input_section(self, parent_layout: QVBoxLayout):
        """
        创建顶部链接输入区域
        """
        # 创建分组框
        url_group = QGroupBox("视频链接")
        url_layout = QHBoxLayout(url_group)
        url_layout.setSpacing(12)
        
        # URL输入框
        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText("请粘贴B站视频链接...")
        self.url_input.setMinimumHeight(40)
        
        # 获取信息按钮
        self.get_info_btn = QPushButton("获取信息")
        self.get_info_btn.setProperty("buttonType", "primary")
        self.get_info_btn.setMinimumSize(120, 40)
        self.get_info_btn.setMaximumSize(120, 40)
        
        url_layout.addWidget(self.url_input)
        url_layout.addWidget(self.get_info_btn)
        
        parent_layout.addWidget(url_group)
        
    def create_video_info_section(self, parent_layout: QVBoxLayout):
        """
        创建视频信息显示区域
        """
        # 创建分组框
        info_group = QGroupBox("视频信息")
        info_layout = QHBoxLayout(info_group)
        info_layout.setSpacing(15)
        
        # 左侧：视频封面
        self.video_cover = QLabel()
        self.video_cover.setFixedSize(160, 120)
        self.video_cover.setStyleSheet(f"""
            QLabel {{
                background-color: {get_color('card_background')};
                border: 2px solid {get_color('border')};
                border-radius: 8px;
                color: {get_color('text_secondary')};
            }}
        """)
        self.video_cover.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.video_cover.setText("📹\n封面")
        
        # 右侧：视频详细信息
        info_details_layout = QVBoxLayout()
        info_details_layout.setSpacing(8)
        
        # 视频标题
        self.video_title = QLabel("等待获取视频信息...")
        self.video_title.setProperty("labelType", "title")
        self.video_title.setWordWrap(True)
        self.video_title.setStyleSheet(f"color: {get_color('text_secondary')};")
        
        # UP主信息
        self.video_author = QLabel("")
        self.video_author.setProperty("labelType", "subtitle")
        
        # 视频时长
        self.video_duration = QLabel("")
        self.video_duration.setProperty("labelType", "caption")
        
        # 清晰度选择
        quality_layout = QHBoxLayout()
        quality_layout.setSpacing(10)
        
        quality_label = QLabel("清晰度:")
        quality_label.setProperty("labelType", "caption")
        
        self.quality_combo = QComboBox()
        self.quality_combo.setMinimumWidth(150)
        self.quality_combo.setEnabled(False)
        
        quality_layout.addWidget(quality_label)
        quality_layout.addWidget(self.quality_combo)
        quality_layout.addStretch()
        
        # 添加到详细信息布局
        info_details_layout.addWidget(self.video_title)
        info_details_layout.addWidget(self.video_author)
        info_details_layout.addWidget(self.video_duration)
        info_details_layout.addLayout(quality_layout)
        info_details_layout.addStretch()
        
        # 添加到主布局
        info_layout.addWidget(self.video_cover)
        info_layout.addLayout(info_details_layout)
        
        parent_layout.addWidget(info_group)
        
    def create_download_settings_section(self, parent_layout: QVBoxLayout):
        """
        创建下载设置区域（重点优化）
        """
        # 创建分组框
        settings_group = QGroupBox("下载设置")
        settings_layout = QVBoxLayout(settings_group)
        settings_layout.setSpacing(15)
        
        # 下载路径设置
        path_layout = QHBoxLayout()
        path_layout.setSpacing(12)
        
        # 标签
        path_label = QLabel("下载至:")
        path_label.setMinimumWidth(60)
        path_label.setProperty("labelType", "subtitle")
        
        # 路径显示文本框（只读）
        self.path_display = QLineEdit()
        self.path_display.setText(self.download_path)
        self.path_display.setReadOnly(True)
        self.path_display.setMinimumHeight(40)
        self.path_display.setStyleSheet(f"""
            QLineEdit {{
                background-color: {get_color('card_background')};
                border: 2px solid {get_color('border')};
                border-radius: 8px;
                padding: 8px 12px;
                font-size: 14px;
                color: {get_color('text_primary')};
            }}
            QLineEdit:focus {{
                border-color: {get_color('border_focus')};
            }}
        """)
        
        # 浏览按钮
        self.browse_btn = QPushButton("📁 浏览...")
        self.browse_btn.setMinimumSize(100, 40)
        self.browse_btn.setMaximumSize(100, 40)
        
        path_layout.addWidget(path_label)
        path_layout.addWidget(self.path_display)
        path_layout.addWidget(self.browse_btn)
        
        settings_layout.addLayout(path_layout)
        
        parent_layout.addWidget(settings_group)
        
    def create_control_buttons_section(self, parent_layout: QVBoxLayout):
        """
        创建操作按钮区域
        """
        # 创建按钮布局
        buttons_layout = QHBoxLayout()
        buttons_layout.setSpacing(15)
        
        # 开始下载按钮
        self.download_btn = QPushButton("🚀 开始下载")
        self.download_btn.setProperty("buttonType", "primary")
        self.download_btn.setMinimumSize(120, 45)
        self.download_btn.setEnabled(False)
        
        # 暂停按钮
        self.pause_btn = QPushButton("⏸️ 暂停")
        self.pause_btn.setMinimumSize(100, 45)
        self.pause_btn.setEnabled(False)
        
        # 停止按钮
        self.stop_btn = QPushButton("⏹️ 停止")
        self.stop_btn.setProperty("buttonType", "danger")
        self.stop_btn.setMinimumSize(100, 45)
        self.stop_btn.setEnabled(False)
        
        # 添加弹性空间
        buttons_layout.addStretch()
        buttons_layout.addWidget(self.download_btn)
        buttons_layout.addWidget(self.pause_btn)
        buttons_layout.addWidget(self.stop_btn)
        buttons_layout.addStretch()
        
        parent_layout.addLayout(buttons_layout)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        self.progress_bar.setMinimumHeight(25)
        parent_layout.addWidget(self.progress_bar)
        
    def create_download_log_section(self, parent_layout: QVBoxLayout):
        """
        创建下载日志区域
        """
        # 创建分组框
        log_group = QGroupBox("下载日志")
        log_layout = QVBoxLayout(log_group)
        log_layout.setSpacing(10)
        
        # 日志区域顶部工具栏
        log_toolbar = QHBoxLayout()
        log_toolbar.setSpacing(10)
        
        log_title = QLabel("实时日志")
        log_title.setProperty("labelType", "subtitle")
        
        # 清空日志按钮
        self.clear_log_btn = QPushButton("🗑️ 清空日志")
        self.clear_log_btn.setMaximumSize(120, 30)
        
        log_toolbar.addWidget(log_title)
        log_toolbar.addStretch()
        log_toolbar.addWidget(self.clear_log_btn)
        
        # 日志文本区域
        self.log_text = QTextEdit()
        self.log_text.setMinimumHeight(200)
        self.log_text.setReadOnly(True)
        self.log_text.setStyleSheet(f"""
            QTextEdit {{
                background-color: {get_color('background')};
                border: 2px solid {get_color('border')};
                border-radius: 8px;
                padding: 12px;
                font-size: 13px;
                color: {get_color('text_primary')};
                font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
                line-height: 1.4;
            }}
        """)
        
        log_layout.addLayout(log_toolbar)
        log_layout.addWidget(self.log_text)
        
        parent_layout.addWidget(log_group)
        
        # 添加初始日志
        self.add_log("系统启动完成，等待用户操作...", "info")
        
    def setup_connections(self):
        """
        设置信号连接
        """
        # 按钮连接
        self.get_info_btn.clicked.connect(self.get_video_info)
        self.browse_btn.clicked.connect(self.browse_download_path)
        self.download_btn.clicked.connect(self.start_download)
        self.pause_btn.clicked.connect(self.pause_download)
        self.stop_btn.clicked.connect(self.stop_download)
        self.clear_log_btn.clicked.connect(self.clear_log)
        
        # URL输入框回车事件
        self.url_input.returnPressed.connect(self.get_video_info)
        
    def get_video_info(self):
        """
        获取视频信息
        """
        url = self.url_input.text().strip()
        if not url:
            self.add_log("请输入视频链接", "warning")
            return
            
        if "bilibili.com" not in url and "b23.tv" not in url:
            self.add_log("请输入有效的B站视频链接", "error")
            return
            
        self.add_log(f"正在获取视频信息: {url}", "info")
        self.get_info_btn.setEnabled(False)
        self.get_info_btn.setText("获取中...")
        
        # TODO: 这里应该调用实际的视频信息获取逻辑
        # 现在先模拟一个成功的响应
        QTimer.singleShot(2000, self.mock_video_info_success)
        
    def mock_video_info_success(self):
        """
        模拟视频信息获取成功
        """
        # 更新视频信息
        self.video_title.setText("【测试视频】这是一个测试视频标题，用于演示界面效果")
        self.video_title.setStyleSheet(f"color: {get_color('text_primary')};")
        self.video_author.setText("UP主: 测试用户")
        self.video_duration.setText("时长: 10:30")
        
        # 更新清晰度选项
        self.quality_combo.clear()
        self.quality_combo.addItems(["1080P 高清", "720P 高清", "480P 清晰", "360P 流畅"])
        self.quality_combo.setCurrentIndex(0)
        self.quality_combo.setEnabled(True)
        
        # 恢复按钮状态
        self.get_info_btn.setEnabled(True)
        self.get_info_btn.setText("获取信息")
        self.download_btn.setEnabled(True)
        
        self.add_log("视频信息获取成功", "success")
        
    def browse_download_path(self):
        """
        浏览下载路径
        """
        folder = QFileDialog.getExistingDirectory(
            self, 
            "选择下载文件夹", 
            self.download_path
        )
        
        if folder:
            self.download_path = folder
            self.path_display.setText(folder)
            self.add_log(f"下载路径已更改为: {folder}", "info")
            
    def start_download(self):
        """
        开始下载
        """
        if not self.video_info and not self.quality_combo.currentText():
            self.add_log("请先获取视频信息", "warning")
            return
            
        self.is_downloading = True
        self.download_btn.setEnabled(False)
        self.pause_btn.setEnabled(True)
        self.stop_btn.setEnabled(True)
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        
        quality = self.quality_combo.currentText()
        self.add_log(f"开始下载视频，清晰度: {quality}", "info")
        
        # TODO: 这里应该启动实际的下载线程
        # 现在先模拟下载进度
        self.simulate_download()
        
    def simulate_download(self):
        """
        模拟下载进度
        """
        self.download_timer = QTimer()
        self.download_progress = 0
        
        def update_progress():
            self.download_progress += 2
            self.progress_bar.setValue(self.download_progress)
            
            if self.download_progress >= 100:
                self.download_timer.stop()
                self.download_complete()
            else:
                self.add_log(f"下载进度: {self.download_progress}%", "info")
                
        self.download_timer.timeout.connect(update_progress)
        self.download_timer.start(200)  # 每200ms更新一次
        
    def download_complete(self):
        """
        下载完成
        """
        self.is_downloading = False
        self.download_btn.setEnabled(True)
        self.pause_btn.setEnabled(False)
        self.stop_btn.setEnabled(False)
        
        self.add_log("下载完成！", "success")
        self.statusBar().showMessage("下载完成")
        
    def pause_download(self):
        """
        暂停下载
        """
        if hasattr(self, 'download_timer'):
            self.download_timer.stop()
            
        self.download_btn.setEnabled(True)
        self.pause_btn.setEnabled(False)
        self.add_log("下载已暂停", "warning")
        
    def stop_download(self):
        """
        停止下载
        """
        if hasattr(self, 'download_timer'):
            self.download_timer.stop()
            
        self.is_downloading = False
        self.download_btn.setEnabled(True)
        self.pause_btn.setEnabled(False)
        self.stop_btn.setEnabled(False)
        self.progress_bar.setVisible(False)
        
        self.add_log("下载已停止", "error")
        
    def clear_log(self):
        """
        清空日志
        """
        self.log_text.clear()
        self.add_log("日志已清空", "info")
        
    def add_log(self, message: str, log_type: str = "info"):
        """
        添加日志消息
        
        Args:
            message: 日志消息
            log_type: 日志类型 (info, success, warning, error)
        """
        import datetime
        
        timestamp = datetime.datetime.now().strftime("%H:%M:%S")
        
        # 根据日志类型设置颜色
        color_map = {
            "info": get_color('text_primary'),
            "success": get_color('success'),
            "warning": get_color('warning'),
            "error": get_color('error')
        }
        
        color = color_map.get(log_type, get_color('text_primary'))
        
        # 格式化日志消息
        formatted_message = f'<span style="color: {color}">[{timestamp}] {message}</span>'
        
        # 添加到日志区域
        self.log_text.append(formatted_message)
        
        # 自动滚动到底部
        scrollbar = self.log_text.verticalScrollBar()
        scrollbar.setValue(scrollbar.maximum())
        
        # 更新状态栏
        self.statusBar().showMessage(message)
        
    def closeEvent(self, event):
        """
        窗口关闭事件
        """
        if self.is_downloading:
            reply = QMessageBox.question(
                self, 
                "确认退出", 
                "正在下载中，确定要退出吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            
            if reply == QMessageBox.StandardButton.No:
                event.ignore()
                return
                
        event.accept()